package book.items.item26;

import java.util.Arrays;
import java.util.EmptyStackException;

public class Stack {
	
	private Object[] elements;
	private int size = 0;
	private static final int DEFAULT_INITIAL_CAPACITY = 16;

	public Stack() {
		this.elements = new Object[DEFAULT_INITIAL_CAPACITY];
	}

	public Object pop() {
		if(isEmpty()) {
			throw new EmptyStackException();
		}
		Object o = elements[--size];
		elements[size] = null;
		return o;
	}
	
	public void push(Object o){
		ensureCapacity();
		elements[size++] = o;
	}
	
	public boolean isEmpty() {
		return size == 0;
	}
	
	private void ensureCapacity() {
		if(elements.length == size) {
			elements = Arrays.copyOf(elements, 2 * size + 1);
		}
	}
}
